from math import ceil

from flask import Flask, request, render_template, jsonify
from waitress import serve

from config.config import get_pro_config
from service.BrowserManager import BrowserManager
from service.LogService import get_logs_for_page
from tools.Result import error_result
from service.AppService import get_data

# 创建 Flask 应用
app = Flask(__name__)


# ========== 路由配置 ==========


@app.route("/api/data", methods=["POST"])
def post_data():
    # 获取JSON数据（自动处理Content-Type）
    json_data = request.get_json(silent=True) or {}

    # 手动处理类型转换
    try:
        pro_type = int(json_data.get("type", 0))  # 修正1：移除关键字参数
    except ValueError:
        return error_result("参数异常")

    detail_url = json_data.get("detail_url")  # 修正2：普通字典的get用法

    # 参数验证
    if pro_type == 0 or not detail_url:
        return error_result("参数异常")

    # 业务处理
    return get_data(pro_type, detail_url)


@app.route('/logs', methods=['GET'])
def logs():
    # 渲染模板
    pro_list=get_pro_config()

    return render_template('index.html',pro_list=pro_list)


@app.route('/api/logs', methods=['GET'])
def logs_api():

    # 获取参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    status = request.args.get('status', None, type=int)
    start_time = request.args.get('startTime', None, type=str)
    end_time = request.args.get('endTime', None, type=str)
    pro_type = request.args.get('proType', None, type=int)

    total, all_data = get_logs_for_page(page, per_page, start_time, end_time, status,pro_type)

    return jsonify({
        'total': total,
        'data': all_data,
        'page': page,
        'per_page': per_page
    })


# ========== 启动服务器 ==========
if __name__ == "__main__":
    serve(app, host="0.0.0.0", port=8966)
